package com.jy.appmarket.screenlock.service;

import com.jy.appmarket.screenlock.utils.CheckMessage;
import com.jy.appmarket.screenlock.utils.LockScreenConfig;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.service.notification.NotificationListenerService;
import android.service.notification.StatusBarNotification;


/**
 * 类说明：
 * 
 * @author  jie.li
 * @date    2015-5-4
 * @version 1.0.0
 */

@SuppressLint("NewApi")
public class SystemNotificationListener extends NotificationListenerService {
    public static final String NOTIFICATION_POSTED = "notification_posted";
    public static final String ACTION_CANCEL_NOTIFICATION = "action_cancel_notification";

    public static final String ACTION_OBTAIN_ACTIVE_NOTIFICATIONS = "action_obtain_active_notification";
 	@Override
	public IBinder onBind(Intent intent) {
        return super.onBind(intent);
	}

	public static void startService(Context context) {
		Intent intent = new Intent(context, SystemNotificationListener.class);
		context.startService(intent);
	}
	public static void stopService(Context context) {
		Intent intent = new Intent(context, SystemNotificationListener.class);
		context.stopService(intent);
	}
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		return START_STICKY;
	}
    @Override
    public void onCreate() {
        super.onCreate();
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        try {
            startService(new Intent(this, SystemNotificationListener.class));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

	@Override
	public void onNotificationPosted(StatusBarNotification sbn) {
		Bundle bundle = sbn.getNotification().extras;
		String title = bundle.getString("android.title");
		String content = bundle.getString("android.text");
		int flag = sbn.getNotification().flags;
		if (LockScreenConfig.isMessageTip(this) && (flag != Notification.FLAG_ONGOING_EVENT || flag != Notification.FLAG_NO_CLEAR)
				&& CheckMessage.checkMessageValid(this, sbn.getPackageName(), title, content)) {
			Intent it = new Intent(ACTION_OBTAIN_ACTIVE_NOTIFICATIONS);
			it.putExtra(NOTIFICATION_POSTED, sbn);
			sendBroadcast(it);
		}
	}

	@Override
	public void onNotificationRemoved(StatusBarNotification arg0) {

	}

}
